<?php

require 'facebook.php';
require 'config.inc.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $fbconfig['app_id'],
  'secret' => $fbconfig['secret_key'],
  'cookie' => true,
));

$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
  } catch (FacebookApiException $e) {
    echo "Somethings wrong";
  }
}

$con = mysql_connect("localhost", "vatsav", "2T*vzcd");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db("vatsav", $con);
if (!$db_selected) {
	die ('Cant use db : ' . mysql_error());
}

//get your groups and friends who are members in that group.

$uid=$_POST["uid"];
$offset = $_POST["offset"];
$limit = $_POST["limit"];


//user's groups and groups user is a member of.
$limit++;
$query = "select uid,groupid,group_name from groups where uid=$uid union select a.uid,a.groupid,a.group_name from groups as a, members as b where 
 b.friendid=$uid and a.uid=b.uid and a.groupid=b.groupid LIMIT $offset,$limit";
$limit--;
$result = mysql_query($query);	

// Check result
if (!$result) {
   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
   echo $message;
}
$num_rows = mysql_num_rows($result);
$i=0;
while($row = mysql_fetch_array($result) )
{
	$i++;
	if($i<=$limit)
	{
		$decoded_group_name = html_entity_decode($row[2],ENT_QUOTES,'UTF-8');
		echo "<div class='topic-block'> <a class='topic-link' onclick='javascript:invite($row[0],$row[1],\"$row[2]\")'> Invite </a> <a class='topic-link' onclick='javascript:group($row[0],$row[1],\"$group_name\",0,4)'>$decoded_group_name</a>"; 
		$query2 = "select friendid from members where groupid=$row[1] and uid=$row[0]";

		$result2 = mysql_query($query2);	
		// Check result
		if (!$result2) {
		   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
		   echo $message;
		}

		while($row2 = mysql_fetch_array($result2))
		{
			if($row2[0]!=$uid)
				echo "<a onclick='javascript:friendProfile($row2[0])'> <img src='https://graph.facebook.com/$row2[0]/picture' /> </a>";
			else
				echo "<a onclick='javascript:friendProfile($row[0])'> <img src='https://graph.facebook.com/$row[0]/picture' /> </a>";
		}
		echo "</div>";
	}
}

?>

<div class="button">

<?php 
	$prev = $offset-$limit;
	$next = $offset+$limit;
	if($offset!=0)
	{
		echo "<a class='simple_button' onclick='javascript:groups($prev,$limit)'>Previous</a> ";
	}
	
	if($limit < $num_rows){
		echo "<a class='simple_button' onclick='javascript:groups($next,$limit)'>Next</a>";
	}
	
mysql_close($con);
?>
</div>
